package study.eggs.async.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

    /* thread pool number, static!!! */
    private static final AtomicInteger POOL_NO = new AtomicInteger(1);

    /* thread number */
    private final AtomicInteger threadNo = new AtomicInteger(1);
    /* thread name prefix （线程名-线程池数量-线程名-线程数量） */
    private final String namePrefix;

    /* thread group */
    private final ThreadGroup group;

    public NamedThreadFactory() {
        this(null);
    }

    public NamedThreadFactory(String name) {
        //pool group
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        //thread name prefix
        if (name != null && !name.isEmpty()) {
            name = name + "-";
        } else {
            name = "";
        }
        namePrefix = String.format("%spool-%s-thread-", name, POOL_NO.getAndIncrement());
    }

    public Thread newThread(Runnable r) {
        //thread name
        String name = String.format("%s-%s", namePrefix, threadNo.getAndIncrement());
        //construct thread
        Thread t = new Thread(group, r, name, 0);
        //set daemon
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        //set priority
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
